<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in suggestions"
      :key="index"
      @click="$emit('search', item)"
      icon="search"
    >
      <span slot="title" v-html="highlight(item)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      // 监视的处理函数 handler是固定写法 不要随便起名字
      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 800),
      // 首次监视触发
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    // 搜索联想事件
    async loadSearchSuggestion (val) {
      try {
        const { data } = await getSearchSuggestion(val)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('无联想')
      }
    },
    // 处理文字高亮
    highlight (text) {
      // console.log(text)
      if (text) {
        const reg = new RegExp(this.searchText, 'gi')
        return text.replace(
          reg,
          `<span style="color: #f00">${this.searchText}</span>`
        )
      } else {
        return '再精确点或者试试其他关键词吧'
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
